<template>
  <div class="article-box">
    <!-- <Guide v-if="showGuide" @hideGuide="hideStep"/> -->
    <div class="article-box-warpper">
      <div class="top isSticky" v-if="isSticky">
        <div class="tab-bar">
          <div class="classify-box">
            <van-tabs
              color="#007AE6"
              :line-width="20"
              v-model="tabactive"
              :line-height="3"
              @click="changeTab"
              title-inactive-color="#9CA5B5"
              title-active-color="#13284D"
            >
              <van-tab v-for="(item, index) in articleType" :title="item.itemName" :key="index"></van-tab>
            </van-tabs>
          </div>
          <div class="icon" @click="showSub1 = !showSub1">
            <img v-show="!showSub1" src="../../assets/img/article/tabicon.png" alt />
            <img v-show="showSub1" src="../../assets/img/article/tabicon2.png" alt />
          </div>
        </div>
        <div class="submenu" v-show="showSub1" @click="showSub1 = false">
          <ul>
            <li
              :class="[{'active': sortType === 2},'scale-1px-bottom']"
              @click="sortTypeFn(2)"
            >按时间排序</li>
            <li :class="{'active': sortType === 1}" @click="sortTypeFn(1)">按活跃度排序</li>
          </ul>
        </div>
      </div>
      <div class="cnt" ref="cnt" @scroll="handleScroll">
        <div class="top" :class="{ isSticky : !dataBar.length && userInfo.token }" >
          <div class="data-bar" v-if="dataBar.length">
            <router-link
              tag="ul"
              class="item-data"
              :class="index ? 'van-hairline--left' : ''"
              v-for="(item, index) in dataBar"
              :key="item.value"
              :to="item.path"
            >
              <li class="name">{{ item.name }}</li>
              <li
                class="num"
                :style="{ color: item.color }"
              >{{ item.unit ? item.unit + item.num : item.num }}</li>
            </router-link>
          </div>
          <div class="tab-bar" ref="tabbar">
          <!-- <div class="tab-bar" :class="{ isSticky : isSticky }"> -->
            <div class="classify-box">
              <van-tabs
                color="#007AE6"
                :line-width="20"
                v-model="tabactive"
                :line-height="3"
                @click="changeTab"
                title-inactive-color="#9CA5B5"
                title-active-color="#13284D"
              >
                <van-tab v-for="(item, index) in articleType" :title="item.itemName" :key="index"></van-tab>
              </van-tabs>
            </div>
            <div class="icon" @click="showSub2 = !showSub2">
              <img v-show="!showSub2" src="../../assets/img/article/tabicon.png" alt />
              <img v-show="showSub2" src="../../assets/img/article/tabicon2.png" alt />
            </div>
          </div>
          <div class="submenu" v-show="showSub2" @click="showSub2 = false">
            <ul>
              <li
                :class="[{'active': sortType === 2},'scale-1px-bottom']"
                @click="sortTypeFn(2)"
              >按时间排序</li>
              <li :class="{'active': sortType === 1}" @click="sortTypeFn(1)">按活跃度排序</li>
            </ul>
          </div>
        </div>
        <div class="article-list" id="article-list" v-if="articleData.length">
          <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
            <van-list
              v-model="loading"
              :finished="finished"
              @load="onLoad"
              finished-text="--没有更多了--"
            >
              <div class="article-item" v-for="(item,index) in articleData" :key="index">
                <div class="article-contaier">
                  <div class="content" @click="goInfo(item)">
                    <div class="left-cnt">
                      <h3 class="title">{{item.articleTitle}}</h3>
                      <div class="attr">
                        <p class="source" v-if="!item.aBoolean">
                          <span class="name">{{item.publisher}}</span>
                          <span class="time">{{item.createTime | formatData}}</span>
                        </p>
                        <p class="source" v-else>
                          <!-- <span class="time">{{item.scanNum | numTransform }}次阅读</span> -->
                          <span class="time">{{item.totalShareAgentCount | numTransform}}人已分享，</span>
                          <span class="time">获客{{item.totalShareCustomerCount | numTransform}}</span>
                        </p>
                        <!-- <span class="read">{{item.scanNum | numTransform }}次阅读</span> -->
                      </div>
                    </div>
                    <div
                      class="img back-image"
                      :style="{backgroundImage: `url(${item.articleImg})` }"
                    ></div>
                  </div>
                </div>
                <div class="share-get van-hairline--top">
                  <div class="tag-part" v-if="item.aBoolean && !!selfSupport">
                    <span class="tag">推广有礼</span>
                    <span
                      class="text"
                    >{{ `每次推广最高获取${ (item.browseDivide / 100 + item.clicksDivide / 100).toFixed(2) }元`}}</span>
                  </div>
                  <span v-else class="text-gray">{{item.scanNum | numTransform }}次阅读</span>
                  <!-- <span
                    v-else
                    class="text-gray"
                  >{{ item.totalShareAgentCount | numTransform}}人已分享，获客{{item.totalShareCustomerCount | numTransform }}</span> -->
                  <span class="button" @click="editClickHandler(item.articleId)">分享拓客</span>
                </div>
              </div>
            </van-list>
          </van-pull-refresh>
        </div>
        <div class="nodata" v-show="!articleData.length && nodataStatus" @click="onRefresh">
          <img src="../../assets/img/article/noarticle.png" alt />
          <p>对不起，没有查询到相关文章！</p>
        </div>
        <div class="artcle-tips" v-show="showNewArticle" @click="onRefresh">
          {{newArticelCount}}条新内容
          <van-icon name="arrow-down" />
        </div>
        <router-link tag="ul" class="add-article" :to="'/discover/newlyAdded'">
          <li class="icon">
            <i class="iconfont icon-zhuanzaiwenzhang"></i>
          </li>
          <li class="title">
            <span>转载文章</span>
          </li>
        </router-link>
      </div>
    </div>
    <Skeleton v-show="showLoading" showSkeleton="3" />
    <red-bags />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Guide from './guide'
import { debounce, isEmpty } from 'lodash'
import commonService from 'SERVICE/commonService'
import ArticleService from 'SERVICE/articleService'
import discoverService from 'SERVICE/discoverService'
import { formatTimeByArticle, parseTime, checkStrLength } from '@/utils/tool'
import redBags from '../wx/money/redbags'
const dataBar = [
  { path: '/custom/addressBook', value: 'todayCustomerCount', color: '#007AE6', name: '今日拓客', num: '0' },
  { path: '/custom/addressBook', value: 'sumCustomerCount', color: '#007AE6', name: '累计拓客', num: '0' },
  { path: '/money/wallet', value: 'todayPrice', color: '#EB602F', name: '今日收益', num: '0', unit: '￥' },
  { path: '/money/wallet', value: 'sumPrice', color: '#EB602F', name: '累计收益', num: '0', unit: '￥' }
]

export default {
  components: {
    Guide,
    redBags
  },
  data() {
    return {
      dataBar: [],
      tabactive: 0,
      newArticelCount: 0,
      showGuide: false, // 显示引导
      articleData: [], // 文章列表
      showSub1: false, // 显示排序菜单
      showSub2: false, // 显示排序菜单
      city: '', // 用户主营城市
      showCity: false, //是否显示城市菜单
      loading: false, //是否处于加载状态
      finished: false, //是否已加载完所有数据
      isLoading: false, //是否处于下拉刷新状态
      showNewArticle: false, // 显示新消息
      articleType: [],
      size: 10,
      current: 1,
      pages: null,
      classify: '3', // 分类
      sortType: 1, // 排序 1：按活跃度排序 2：按文章创建时间排序
      classifyName: '热点', // 分类
      showLoading: false, // loading
      nodataStatus: false,
      getDataStatus: false,
      selfSupport: '',
      isSticky: false
    }
  },
  filters: {
    numTransform(val) {
      if (val < 1000) return val
      return (val / 1000).toFixed(1) + 'K'
    },
    formatData(time) {
      return time ? formatTimeByArticle(time) : '-'
    }
  },
  watch: {
    '$store.getters.newMsgStatus': function(v) {
      let msgContent = this.$store.getters.newMsgContent
      if (!v) {
        this.showNewArticle = false
      } else {
        if (msgContent.desc == 6 && this.$route.path == '/write-article') {
          let data = JSON.parse(msgContent.data)
          this.newArticelCount = data.newArticleCount
          this.showNewArticle = v
          return
        }
      }
    },
    articleData() {
      if (this.articleData.length) {
        this.$nextTick(function() {
          let top = window.sessionStorage.getItem('scrollTop') || 0
          if (top > 0) {
            document.querySelector('.cnt').scrollTop = top
            window.sessionStorage.removeItem('scrollTop')
          }
        })
      }
    }
  },
  async created() {
    this.showGuide = this.userInfo.articleEditFlag !== 1 // !JSON.parse(window.localStorage.getItem('guideStatus'))
    let storage = JSON.parse(window.sessionStorage.getItem('tab')) || { itemCode: '3', itemName: '10万+' }
    this.classifyName = storage.itemName
    this.classify = storage.itemCode
    let tabActive = sessionStorage.getItem('tabActive')
    this.tabactive = tabActive ? tabActive : tabActive == null ? 0 : 1
    this.enterpriseId = localStorage.getItem('enterpriseId') || this.userInfo.enterpriseId
    sessionStorage.removeItem('easyLookChildListUrl')
    sessionStorage.removeItem('historicalArticlesUrl')
    if (this.userInfo && this.userInfo.token) {
      let totalData = await ArticleService.getArticleTotalData()
      dataBar.forEach(item => {
        let key = item.value
        item.num = totalData[key]
      })
      this.selfSupport = this.userInfo.selfSupport
      // 0为第三方  1是AW大师自营
      if (!this.selfSupport) {
        this.dataBar = dataBar.slice(0, 2)
      } else {
        this.dataBar = dataBar
      }
    } else {
      // 未登录状态默认为1，显示推广有礼标识
      this.selfSupport = localStorage.getItem('selfSupport')
    }
    this.changeClassify(storage.itemCode, storage.itemName)
  },
  computed: {
    ...mapGetters(['userInfo']),
    system() {
      let u = navigator.userAgent,
        app = navigator.appVersion
      let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 //g
      let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) //ios终端
      if (isAndroid) {
        return 'Android'
      } else if (isIOS) {
        return 'IOS'
      } else {
        return ''
      }
    }
  },
  methods: {
    handleScroll() {
      let scrollTop = this.$refs.cnt.scrollTop
      if (!this.offsetTop) this.offsetTop = this.$refs.tabbar.offsetTop
      if (scrollTop < this.offsetTop) {
        this.isSticky = false
      } else {
        this.isSticky = true
      }
    },
    editClickHandler(id) {
      window.sessionStorage.setItem('scrollTop', document.querySelector('.cnt').scrollTop)

      let area = this.userInfo.majorCity ? this.userInfo.majorCity : '全国'
      this.$router.push({ path: `/discover/edit/${id}/${area}`, query: { agentId: this.userInfo.agentId, enterpriseId: this.enterpriseId } })
    },
    // 更新新手引导标志位
    updateUserExpandInfo() {
      commonService.updateUserExpandInfo({ articleEditFlag: 1 })
      let data = Object.assign({}, this.userInfo, { articleEditFlag: 1 })
      this.$store.dispatch('getUserInfo', data)
    },
    // 隐藏引导页
    hideStep() {
      this.showGuide = false
      this.updateUserExpandInfo()
      // window.localStorage.setItem('guideStatus', true)
    },
    // 获取文章分类
    async getArticleType() {
      let result = await ArticleService.getArticleType({ classify: 'information_classify', enterpriseId: this.enterpriseId })
      if (result) {
        result.splice(1, 0, { itemCode: '', itemName: '热点' })
        this.articleType = result
        window.sessionStorage.setItem('type', JSON.stringify(this.articleType))
      }
    },
    // 获取文章列表
    async getArticleList() {
      if (!this.articleData.length) {
        this.showLoading = true
      }
      this.nodataStatus = false
      // if (!sortType) {
      //   sortType = this.classifyName === '热点' ? 1 : 2
      // }
      this.getDataStatus = true
      let lizeGift = await ArticleService.getGeneralizeGift({ agentId: this.userInfo.agentId, enterpriseId: this.enterpriseId, uuid: this.userInfo.uuid })
      let result = await ArticleService.getArticleList({
        current: this.current,
        size: this.size,
        // city: this.userInfo.majorCity ? this.userInfo.majorCity : '全国',
        city: '',
        classify: this.classify,
        sortType: this.sortType,
        enterpriseId: this.enterpriseId
      })
      if (result) {
        this.pages = result.pages
        let records = result.records.map(item => {
          return Object.assign(item, { likeCount: 15, replayCount: 5, ...lizeGift })
        })
        if (this.current === 1) {
          this.articleData = records
        } else {
          this.articleData.push(...records)
        }
        this.current += 1
      }
      this.nodataStatus = true
      this.showLoading = false
      this.getDataStatus = false
    },
    // 重新获取位置
    async getLocation() {
      await this.$wechatHelper.getUserArea()
    },
    changeTab(name, title) {
      sessionStorage.setItem('tabActive', name)
      this.changeClassify(name, title)
    },
    // tab切换 文章分类查询
    changeClassify(name, title) {
      // 数据请求禁止切换
      if (this.getDataStatus) {
        return false
      }
      let type = JSON.parse(window.sessionStorage.getItem('type'))
      let itemCode = name
      if (type) {
        for (const item of type) {
          if (item.itemName == title) {
            itemCode = item.itemCode
            break
          }
        }
      }
      let item = {
        itemCode: itemCode,
        itemName: title
      }
      window.sessionStorage.setItem('tab', JSON.stringify(item))
      this.finished = false
      this.cacheDataFn(item)
    },
    // 缓存数据
    cacheDataFn(item) {
      // 缓存上一个tab的数据
      let cacheData = JSON.parse(window.sessionStorage.getItem('cacheData')) || {}
      if (this.articleData.length) {
        cacheData[this.classifyName] = {
          classify: this.classify,
          classifyName: this.classifyName,
          current: this.current,
          articleData: this.articleData,
          pages: this.pages
        }
        window.sessionStorage.setItem('cacheData', JSON.stringify(cacheData))
      }
      let data = cacheData[item.itemName]
      if (data && data.articleData && data.articleData.length) {
        this.classify = data.classify
        this.classifyName = data.classifyName
        this.current = data.current
        this.articleData = data.articleData
        this.pages = data.pages
      } else {
        this.classify = item.itemCode
        this.classifyName = item.itemName
        this.current = 1
        this.articleData = []
        this.getArticleList()
      }
    },
    // 显示按时间排序菜单
    // showSubFn() {
    //   this.showSub = !this.showSub
    //   if (this.showSub) {
    //     this.$store.commit('TABBAR', { show: false })
    //   } else {
    //     this.$store.commit('TABBAR', { show: true })
    //   }
    // },
    // 隐藏时间排序菜单
    // hideSubMenu() {
    //   this.showSub = false
    //   // this.$store.commit('TABBAR', { show: true })
    // },
    // 按时间菜单排序
    sortTypeFn(val) {
      if (this.sortType === val) {
        return false
      }
      this.current = 1
      this.sortType = val
      this.articleData = []
      this.getArticleList(val)
    },
    // 跳转文章详情
    goInfo(item) {
      if (this.userInfo && this.userInfo.token) {
        window.sessionStorage.setItem('scrollTop', document.querySelector('.cnt').scrollTop)
        item.scanNum += 1
        let articleId = item.articleId
        let area = this.classifyName === this.userInfo.majorCity ? this.userInfo.majorCity : '全国'
        let agentId = this.userInfo.agentId
        let enterpriseId = this.userInfo.enterpriseId
        let classify = this.classify
        this.$router.push(`/discover/${articleId}/${area}?agentId=${agentId}&enterpriseId=${enterpriseId}`)
      } else {
        let uuid = window.localStorage.getItem('uuid')
        let enterpriseId = window.localStorage.getItem('enterpriseId')
        this.$router.push(`/wx/login?uuid=${uuid}&enterpriseId=${enterpriseId}&toPath=/write-article`)
      }
      
    },
    // 去新增文章页面
    goAdd() {
      this.$router.push({ name: 'addLinker' })
    },
    // 去我的写一写
    goWrite() {
      this.$router.push('/user/articles/historicalArticles')
    },
    // 加载更多
    async onLoad() {
      if (this.current > this.pages) {
        // 加载状态结束
        this.finished = true
        this.loading = false
      } else {
        await this.getArticleList()
        this.loading = false
      }
    },
    // 下拉刷新
    async onRefresh() {
      this.current = 1
      this.pages = 0
      // this.articleData = []
      this.showNewArticle = false
      window.sessionStorage.setItem('scrollTop', 0)
      await this.getArticleList()
      this.isLoading = false
    },
    goBack() {
      this.$router.replace({ path: '/dynamics' })
    }
  },
  mounted() {
    let type = JSON.parse(window.sessionStorage.getItem('type'))
    if (type) {
      this.articleType = type
    } else {
      this.getArticleType()
    }
    if (window.history && window.history.state) {
      history.pushState(null, null, document.URL)
      window.addEventListener('popstate', this.goBack, false)
    }
  },
  beforeDestroy() {
    // 缓存数据
    this.cacheDataFn({ itemCode: this.classify, itemName: this.classifyName })
  },
  destroyed() {
    window.removeEventListener('popstate', this.goBack, false)
  }
}
</script>

<style lang="less" scoped>
/deep/ .van-tabs {
  .van-tab--active {
    font-weight: bold;
  }
  .van-hairline--top-bottom::after {
    border: none;
  }
}

// .scale-1px-hairline--bottom::after {
//   background: #e4e6f0;
// }
.article-box {
  height: 100%;
  width: 100%;
  display: flex;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  font-family: 'Microsoft YaHei', 'PingFangSC-Regular';
  font-size: 16px;
  .article-box-warpper {
    background: #f7f9fa;
    position: relative;
    flex: 1;
    display: flex;
    flex-direction: column;
    .cnt {
      flex: 1;
      overflow-y: scroll;
    }
    .write {
      width: 56px;
      position: absolute;
      right: 12px;
      bottom: 0;
      z-index: 10;
    }
  }
  .data-bar {
    padding: 16px 0;
    display: flex;
    color: #13284d;
    background: #fff;
    justify-content: center;
    margin-bottom: 4px;
    .item-data {
      flex: 1;
      text-align: center;
      .name {
        font-size: 14px;
        line-height: 20px;
        padding-bottom: 5px;
      }
      .num {
        font-size: 16px;
        line-height: 22px;
        font-weight: 500;
      }
    }
  }
  .tab-bar {
    padding: 0 16px;
    height: 44px;
    box-sizing: border-box;
    overflow: hidden;
    background-color: #fff;
    position: relative;
    width: 100%;
    .classify-box {
      // overflow-y: hidden;
      // overflow-x: scroll;
      width: 300px;
      overflow: hidden;
    }
    .icon {
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      right: 0;
      width: 24px;
      height: 24px;
      top: 10px;
      right: 16px;
      margin-right: 0;
      text-align: center;
      img {
        width: 18px;
        height: 17px;
      }
    }
  }
  .isSticky{
    width: 100%;
    position: fixed;
    z-index: 100;
    top: 0;
    left: 0;
  }
  
  .submenu {
    position: fixed;
    top: 127px;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    box-shadow: 0px 0px 6px 0px rgba(58, 76, 130, 0.1);
    z-index: 4;
    ul {
      position: relative;
      background-color: #fff;
      li {
        height: 50px;
        line-height: 50px;
        padding: 0 16px;
        &.active {
          color: #007ae6;
        }
      }
    }
  }
  .isSticky {
    .submenu {
      top: 44px;
    }
  }
  .article-list {
    .article-item {
      background: #fff;
      margin: 10px 0;
      // box-shadow: 0px 0px 6px 0px rgba(58, 76, 130, 0.1);
      // border-radius: 6px;
      overflow: hidden;
      .article-contaier {
        overflow: hidden;
        padding: 16px;
      }
      .share-get {
        font-size: 12px;
        padding: 12px 0;
        margin: 0 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .tag-part {
          display: flex;
          align-items: center;
        }
        .tag {
          color: #fff;
          // width: 56px;
          text-align: center;
          line-height: normal;
          background: #eb602f;
          padding: 3px 4px;
          border-radius: 4px 0px 0px 4px;
        }
        .text {
          line-height: normal;
          color: #eb602f;
          background: #fdefea;
          padding: 3px 4px 3px 10px;
          width: 206px;
          border-radius: 0px 4px 4px 0px;
        }
        .text-gray {
          color: #345276;
        }
        .button {
          color: #fff;
          background: #007ae6;
          line-height: normal;
          padding: 4px 8px;
          border-radius: 4px;
        }
      }
      .content {
        display: flex;
        overflow: hidden;
        .left-cnt {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          margin-right: 15px;
          .title {
            font-size: 16px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2; //（行数）
            -webkit-box-orient: vertical;
            // padding-top: 14px;
            line-height: 24px;
            min-height: 48px;
            color: #13284d;
            word-break: break-all;
          }
          .attr {
            color: #969ea8;
            font-size: 12px;
            display: flex;
            align-items: center;
            .source {
              flex: 1;
              .name {
                display: inline-block;
                margin-right: 12px;
                max-width: 60px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                vertical-align: middle;
              }
              .time {
                display: inline-block;
                vertical-align: middle;
              }
            }
            .read {
              line-height: 16px;
              min-width: 60px;
              text-align: right;
              display: inline-block;
              vertical-align: middle;
            }
          }
        }
        .img {
          width: 104px;
          height: 78px;
          border-radius: 6px;
          overflow: hidden;
          // margin-top: 16px;
          img {
            min-width: 100%;
            min-height: 100%;
            border-radius: 6px;
            object-fit: cover;
          }
        }
        .back-image {
          background-position: center;
          background-repeat: no-repeat;
          background-size: cover;
        }
      }
    }
  }
  .nodata {
    padding-top: 160px;
    text-align: center;
    color: #999;
    font-size: 12px;
    img {
      width: 88px;
      height: 88px;
      margin-bottom: 5px;
    }
  }
  .artcle-tips {
    width: 120px;
    height: 36px;
    background-color: #007ae6;
    color: #fff;
    text-align: center;
    line-height: 36px;
    border-radius: 4px;
    font-size: 14px;
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
    top: 4px;
  }
  .add-article {
    position: absolute;
    bottom: 24px;
    right: 24px;
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: #007ae6;
    .icon {
      text-align: center;
      padding-top: 6px;
      i {
        font-size: 32px;
        color: #fff;
      }
    }
    .title {
      font-size: 10px;
      text-align: center;
      color: #fff;
    }
  }
  .loading {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 50px;
    background-color: rgba(0, 0, 0, 0.1);
    z-index: 5;
    .van-loading {
      display: inline-block;
      position: fixed;
      left: 50%;
      top: 50%;
      width: 50px;
      height: 50px;
      z-index: 5;
      margin-left: -25px;
      margin-top: -25px;
    }
  }
  .comment-like-dialog {
    position: fixed;
    width: 200px;
    height: 45px;
    color: #fff;
    // left: 50%;
    // transform: translateX(-50%);
    text-align: center;
    z-index: 3;
    .arrow-up {
      width: 0;
      height: 0;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-bottom: 5px solid #4b5154;
      position: relative;
      left: 50%;
    }
    .action {
      position: relative;
      background-color: #4b5154;
      height: 40px;
      border-radius: 6px;
      font-size: 14px;
      vertical-align: middle;
      line-height: 40px;
      display: flex;
      span {
        flex: 1;
        img {
          width: 16px;
          height: 16px;
          vertical-align: middle;
          position: relative;
          top: -1px;
          margin-right: 2px;
        }
      }
    }
  }
}
</style>
